package com.website.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.website.common.util.WebUtil;
import com.website.common.vo.Result;
import com.website.mybatis.entity.SysUser;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.MediaType;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义uri权限拦截
 *
 * @author zhangshuw
 * @date 2018/7/17
 */
public class PermissionFilter extends AuthorizationFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request,
                                      ServletResponse response, Object mappedValue) {
        //先判断带参数的权限判断
        Subject subject = getSubject(request, response);
        Object user = subject.getPrincipal();
        if (user instanceof SysUser) {
            SysUser u = (SysUser) user;
            if (u.getAdmin()) {
                //超级管理员有所有权限
                return Boolean.TRUE;
            }
        }
        if (null != mappedValue) {
            String[] arr = (String[]) mappedValue;
            for (String permission : arr) {
                if (subject.isPermitted(permission)) {
                    return Boolean.TRUE;
                }
            }
        }
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String uri = httpRequest.getRequestURI().replaceAll("//", "/");
        //获取URI
        String basePath = httpRequest.getContextPath();
        //获取basePath
        if (uri.startsWith(basePath)) {
            uri = uri.replace(basePath, "");
        }
        return subject.isPermitted(uri);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        Subject subject = getSubject(request, response);
        // If the subject isn't identified, redirect to login URL
        if (subject.getPrincipal() == null) {
            saveRequestAndRedirectToLogin(request, response);
        } else if (WebUtil.isAjax(request)) {
            //ajax请求不跳转
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().print(JSON.toJSONString(Result.error("当前用户权限不足")));
        } else {
            String unauthorizedUrl = getUnauthorizedUrl();
            if (StringUtils.hasText(unauthorizedUrl)) {
                WebUtils.issueRedirect(request, response, unauthorizedUrl);
            } else {
                WebUtils.toHttp(response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        }
        return false;
    }
}
